module("myjson", package.seeall);

ssid = nil
pwd = nil
mqttIP = nil

function readJsonFromfile()
    if file.open("config.json") then
        filedata = file.read()
        --print(filedata)
        file.close()
    end
    
    -- json --> table
    local t = sjson.decode(filedata)
    for k, v in pairs(t) do 
        --print(k, v)
        if (k == 'ssid') then
            ssid = v
        elseif k == 'pwd' then
            pwd = v
        elseif k == 'mqttIP' then
            mqttIP = v
        end
    end
end

function readJson(filedata)
    -- json --> table
    local t = sjson.decode(filedata)
    for k, v in pairs(t) do 
        --print(k, v)
        if (k == 'ssid') then
            ssid = v
        elseif k == 'pwd' then
            pwd = v
        elseif k == 'mqttIP' then
            mqttIP = v
        end
    end
end

function WriteJson(ssid, pwd, mqttIP)
    local ledtable = {}
    ledtable.ssid=ssid
    ledtable.pwd=pwd
    ledtable.mqttIP=mqttIP
    
    -- table --> json
    local ok, json = pcall(sjson.encode, ledtable)
    if ok then
        file.remove("config.json");
        local fw = file.open("config.json","w+");
        if fw then
            file.writeline(json)
            file.close()
        end
        --print(json)
    end
end
